﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace TSB.SharePointUrlShortener.DAL
{
    public class UrlShortenerRepository
    {
        public Dictionary<string,string> GetAllShortcodes()
        {
            var shortCodes = new Dictionary<string, string>();

            var query = new SPQuery
            {
                Query = "<OrderBy Name='Title' />"
            };
            
            var urlShortenerList = SPContext.Current.Site.RootWeb.Lists.TryGetList(Constants.LIST_URLSHORTENER);

            if (urlShortenerList == null)
            {
                return shortCodes;
            }

            var urls = urlShortenerList.GetItems(query);

            if (urls == null || urls.Count == 0)
            {
                return shortCodes;
            }

            foreach(SPListItem item in urls)
            {
                var shortCode = item[Constants.LIST_URLSHORTENER_Title] != null ? item[Constants.LIST_URLSHORTENER_Title].ToString() : string.Empty ;

                if (shortCodes.ContainsKey(shortCode))
                {
                    continue;
                }

                shortCodes.Add(shortCode, item[Constants.LIST_URLSHORTENER_URL] != null ? item[Constants.LIST_URLSHORTENER_URL].ToString() : string.Empty);
            }

            return shortCodes;
        }

        public string GetRedirectFromShortcode(string shortCode)
        {
            if (string.IsNullOrEmpty(shortCode))
            {
                return string.Empty;
            }

            var query = new SPQuery
                            {
                                Query = string.Format("<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where>", shortCode),
                                RowLimit = 1
                            };


            var urlShortenerList = SPContext.Current.Site.RootWeb.Lists.TryGetList(Constants.LIST_URLSHORTENER);

            if (urlShortenerList == null)
            {
                return string.Empty;
            }

            var url = urlShortenerList.GetItems(query);

            if (url == null || url.Count == 0)
            {
                return string.Empty;
            }

            return url[0][Constants.LIST_URLSHORTENER_URL] != null
                       ? url[0][Constants.LIST_URLSHORTENER_URL].ToString()
                       : string.Empty;
        }

        public bool CheckShortcodeExists(string shortCode, out string urlResponse)
        {
            var tempResponse = string.Empty;

            return CheckExists(shortCode, Constants.LIST_URLSHORTENER_Title, out tempResponse, out urlResponse);
        }

        public bool CheckUrlExists(string url, out string shortcodeResponse)
        {
            var tempResponse = string.Empty;

            return CheckExists(url, "Url", out shortcodeResponse, out tempResponse);
        }

        bool CheckExists(string input, string field, out string shortcodeResponse, out string urlResponse)
        {
            shortcodeResponse = string.Empty;
            urlResponse = string.Empty;

            if (string.IsNullOrEmpty(input))
            {
                return false;
            }

            var query = new SPQuery
            {
                Query = string.Format("<Where><Eq><FieldRef Name='{1}'/><Value Type='Text'>{0}</Value></Eq></Where>", input, field),
                RowLimit = 1
            };


            var urlShortenerList = SPContext.Current.Site.RootWeb.Lists.TryGetList(Constants.LIST_URLSHORTENER);

            if (urlShortenerList == null)
            {
                return false;
            }

            var url = urlShortenerList.GetItems(query);

            if (url == null || url.Count == 0)
            {
                return false;
            }

            shortcodeResponse = url[0][Constants.LIST_URLSHORTENER_Title] != null ? url[0][Constants.LIST_URLSHORTENER_Title].ToString() : string.Empty;
            urlResponse = url[0][Constants.LIST_URLSHORTENER_URL] != null ? url[0][Constants.LIST_URLSHORTENER_URL].ToString() : string.Empty;
            return true;
        }

        public bool DeleteByUrl(string url)
        {
            return Delete(url, "Url");
        }

        public bool DeleteByShortcode(string shortCode)
        {
            return Delete(shortCode, "Title");
        }

        private bool Delete(string value, string field)
        {
            if (string.IsNullOrEmpty(value))
            {
                return false;
            }

            var query = new SPQuery
            {
                Query = string.Format("<Where><Eq><FieldRef Name='{1}'/><Value Type='Text'>{0}</Value></Eq></Where>", value, field),
                RowLimit = 1
            };


            var urlShortenerList = SPContext.Current.Site.RootWeb.Lists.TryGetList(Constants.LIST_URLSHORTENER);

            if (urlShortenerList == null)
            {
                return false;
            }

            var existingUrls = urlShortenerList.GetItems(query);

            if (existingUrls == null || existingUrls.Count == 0)
            {
                return false;
            }

            try
            {
                var tempWeb = existingUrls[0].Web;
                tempWeb.AllowUnsafeUpdates = true;
                existingUrls[0].Delete();
                tempWeb.AllowUnsafeUpdates = false;
            }
            catch
            {
                return false;
            }

            return true;
        }

        public bool CreateShortener(string shortcode, string url)
        {
            var urlShortenerList = SPContext.Current.Site.RootWeb.Lists.TryGetList(Constants.LIST_URLSHORTENER);

            if (urlShortenerList == null)
            {
                return false;
            }

            var item = urlShortenerList.AddItem();
            item[Constants.LIST_URLSHORTENER_Title] = shortcode;
            item[Constants.LIST_URLSHORTENER_URL] = url;
            item.Update();

            return true;
        }


        public string GenerateShortCode()
        {
            var rnd = new Random();
            var chars = new ArrayList
                            {
                                "a",
                                "b",
                                "c",
                                "d",
                                "e",
                                "f",
                                "g",
                                "h",
                                "i",
                                "j",
                                "k",
                                "l",
                                "m",
                                "n",
                                "o",
                                "p",
                                "q",
                                "r",
                                "s",
                                "t",
                                "u",
                                "v",
                                "w",
                                "x",
                                "y",
                                "z"
                            };
            var shortCode = string.Empty;

            for (var i = 0; i < 7; i++)
            {
                shortCode += chars[rnd.Next(0, 25)];
            }

            return shortCode;
        }
    }
}
